package shs.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
   private ObjectMapper mapper = null;//把对象转出yaml
   public MyYamlHttpMessageConverter() {
       //支持那种媒体类型
       super(new MediaType("application", "yaml", StandardCharsets.UTF_8));
        YAMLFactory factory=new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
        this.mapper = new ObjectMapper(factory);
   }
    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override  //@RequestBody,把对象写进去
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override  //@ResponseBody,把对象怎么写出去
    protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //try-with写法，自动关流
         try(OutputStream os=outputMessage.getBody()) {
             this.mapper.writeValue(os, methodReturnValue);
         }
    }
}
